#!/bin/bash
thisScriptDir=$(cd $(dirname ${BASH_SOURCE}) && pwd)
cd ${thisScriptDir}


if [[ $EUID -ne 0 ]];then
    if command -v sudo >/dev/null 2>&1;then
        echo "Not run as root,try sudo cmd..."
        sudo true || { echo "cannot use sudo cmd.";exit 1; }
    else
        echo "Not run as root ,and no sudo command."
        exit 1
    fi
fi

#能够走到这里,说明要么是root,要么有sudo权限
if [[ $EUID -ne 0 ]];then
    APT="sudo apt"
else
    APT="apt"
fi

source functions

if [[ "$(uname)" == "Darwin" ]] && [[ $EUID -eq 0 ]];then
	echo "On MacOS,don't use sudo to install supervim."
	exit 1
fi
user=${SUDO_USER:-$(whoami)}
HOME=$(eval echo ~$user)
help=0
proxy=""
localProxy=""
vimGo=0
ycm=0
font=0
downloadFromNAS=0

whichVim=""
cfg=""
root=""
#options:
#h  help
#g  vimgo
#l  local socks5 proxy
#p  "socks5://ip:port" external socks5 proxy
#y  1:clang 2:golang 3:both  ycm
#f  install font
#d download from NAS
while getopts "hglp:y:fd" opt;do
    case "$opt" in
        h)
            help=1
            ;;
        g)
            vimGo=1
            ;;
        d)
        downloadFromNAS=1
            ;;
        l)
            localProxy="socks5://localhost:1080"
            ;;
        p)
            proxy=$OPTARG
            ;;
        y)
            ycm=$OPTARG
            ;;
        f)
            font=1
            ;;
        *)
            help
            ;;
    esac
done

if (($help==1));then
    help
    exit 0
fi
if [[ $ycm -ne 0 ]] && [[ $ycm -ne 1 ]] && [[ $ycm -ne 2 ]] && [[ $ycm -ne 3 ]];then
    echo  "-y valid argument is: 0 (not install ) 1 (for clang) 2 (for golang) 3 (for both)"
    exit 1
fi
#-l override -p flag
if [[ -n $localProxy ]];then
    proxy=$localProxy
fi

shift $((OPTIND-1))
case $(uname) in
    Linux)
        if command -v apt >/dev/null 2>&1;then
            "$APT" update
        fi
        ;;
esac
#install bc command
if ! command -v bc >/dev/null 2>&1;then
    echo "Install bc..."
    #debian
    if command -v $APT >/dev/null 2>&1;then
        if [[ $EUID -ne 0 ]];then
            sudo "$APT" install -y bc >/dev/null 2>&1
        else
            "$APT" install -y bc >/dev/null 2>&1
        fi
    fi
fi

if ! command -v bc >/dev/null 2>&1;then
    echo "Install bc failed,install it manually."
    exit 1
fi

whichVim=$1
if [[ "$whichVim" == "nvim" ]];then
    root=$HOME/.config/nvim
    cfg="$root/init.vim"
elif [[ "$whichVim" == "vim" ]];then
    root=$HOME/.vim
    cfg=$HOME/.vimrc

    GREP=grep
    if [[ "$(uname)" == "Darwin" ]];then
        GREP=ggrep
    fi
    version=$(\vim --version | $GREP -Po '(?<=Vi IMproved )\d+\.\d+')
    echo "vim version is ${version}"
    if (( $(echo "$version>=7.4" | bc -l) )) ;then
        #vim 7.4以后，vimrc文件可以放到.vim目录中
        cfg="$root/vimrc"
    fi
    if [[ $ycm -ne 0 ]];then
        if (( $(echo "$version<=7.4" | bc -l) )) ;then
            #vim 7.4以后，YouCompleteMe才支持
            echo "YouCompleteMe need vim version greater 7.4"
            echo "So,not install YouCompleteMe."
            ycm=0
        fi
    fi
else
    echo "Unknown vim type:  Not vim or nvim."
    echo "Usage: $(basename $0) [options] vim|nvim"
    exit 1
fi

if ! command -v $whichVim >/dev/null 2>&1;then
    "$APT" install -y $whichVim >/dev/null 2>&1
fi
checkCmd $whichVim

echo "Install supervim for $whichVim"
echo "Config file is $cfg"
echo "Root dir is $root"

if ! command -v curl >/dev/null 2>&1;then
    "$APT" install -y curl >/dev/null 2>&1
fi

checkCmd curl

CURL=curl
if [ -n "$proxy" ];then
    CURL="curl --socks5 $proxy"
    echo "set git proxy to $proxy"
    git config --global http.proxy "$proxy"
    git config --global https.proxy "$proxy"
fi

if [[ "$font" -eq 1 ]];then
    installFont
fi

installBasic

#ycm和vimgo是可选的,如果安装的话,则先把vimrc中的他们的注释去掉
if (($ycm!=0));then
    #1 去掉注释
    sed -ibak "s|\"[ ]*\(Plug 'Valloric/YouCompleteMe'\)|\1|" $cfg
    rm -f "${cfg}bak"

    if [[ "$whichVim" == "vim" ]];then
        dest="$HOME/.vim/plugins/YouCompleteMe"
    elif [[ "$whichVim" == "nvim" ]];then
        dest="$HOME/.config/nvim/plugins/YouCompleteMe"
    fi
    #2 根据ycm的值,安装不同的依赖
    #common: need CMake clang python or python3
    #golang: need go

    #ycm不是0,就一定是1或2或3,因为上面有检查
    if [[ $ycm -ne 0 ]];then
        if ! command -v cmake >/dev/null 2>&1;then
            "$APT" install -y cmake
        fi
        if ! command -v clang >/dev/null 2>&1;then
            "$APT" install -y clang
        fi
        if ! command -v python3 >/dev/null 2>&1;then
            "$APT" install -y python3
        fi
    fi
    if [[ $ycm -eq 2 ]];then
        if ! command -v go >/dev/null 2>&1;then
            "$APT" install -y golang
        fi
    fi
    if [[ "$downloadFromNAS" -eq 1 ]];then
        #3 从我的nas下载YouCompleteMe
        echo "Download YouCompleteMe from NAS..."
        curl -L -o YouCompleteMe.tar.gz http://home.eagle711.win:5000/fbsharing/I0CloRro
        echo "Extract YouCompleteMe..."
        tar -C $root/plugins -xf YouCompleteMe.tar.gz
        rm -rf YouCompleteMe.tar.gz
    fi
fi

if (($vimGo==1));then
    echo "modify $cfg for vim-go"
    sed -ibak "s|\"[ ]*\(Plug 'fatih/vim-go'\)|\1|" $cfg
    rm -f "${cfg}bak"
    echo "Set GOPATH to ~/go"
    export GOPATH=~/go
    if [[ ! -d $GOPATH ]];then
        mkdir -pv $GOPATH
    fi
    if [[ "$downloadFromNAS" -eq 1 ]];then
        echo "Download vim-go source from NAS..."
        curl -L -o vimgosrc.tar.gz http://home.eagle711.win:5000/fbsharing/OHdvYwf9
        echo "Extract..."
        tar -C $GOPATH -xf vimgosrc.tar.gz
        rm -rf vimgosrc.tar.gz
        echo "ls GOPATH"
        ls $GOPATH
    fi
    #install go if needed
    if ! command -v go >/dev/null 2>&1;then
        if [[ "$downloadFromNAS" -eq 1 ]];then
            curl -L -o go1.8.3.linux-amd64.tar.gz http://home.eagle711.win:5000/fbsharing/YHzaDviP
            tar -C /usr/local -xf go1.8.3.linux-amd64.tar.gz
            rm -rf go1.8.3.linux-amd64.tar.gz
            cd /usr/local/bin
            for i in $(ls ../go/bin/*);do
                ln -sf $i .
            done
            cd -
        else
            "$APT" install -y golang
        fi
    fi
fi

echo "Install plugins..."
#$whichVim +PlugInstall +qall
$whichVim -c PlugInstall -c qall

if (($ycm!=0));then
    echo "Install YouCompleteMe..."
    if [ -d "$dest" ];then
        cd "$dest"
        option=
        #ycm 1:clang 2:golang 3:both
        if [[ $ycm -eq 1 ]];then
            option+=" --clang-completer "
            option+=" --system-libclang "
        elif [[ $ycm -eq 2 ]];then
            option+=" --gocode-completer "
        elif [[ $ycm -eq 3 ]];then
            option+=" --clang-completer "
            option+=" --system-libclang "
            option+=" --gocode-completer "
        fi
        #./install.py  --gocode-completer --clang-completer --system-libclang
        eval python3 ./install.py  "$option" || { echo "Install YouCompleteMe failed."; exit 1; }
    else
        echo "Doesn't exist $dest"
        exit 1
    fi
fi

if (($vimGo==1));then
    echo "Install vim-go..."
    #$whichVim +GoInstallBinaries +qall
    $whichVim -c GoInstallBinaries -c qall
    templateFile=$(find $root -name hello_world.go)
    SED=sed
    if [[ "$(uname)" == "Darwin" ]];then
        SED=gsed
    fi
    $SED -ibak  's|"fmt"|(\n    &\n)|' "$templateFile"
    rm "$templateFile"bak
fi
